package ntd.util.modular.other.controller;

import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import ntd.task.TaskManager;
import ntd.task.bo.TaskInfo;
import ntd.util.config.common.bo.RequestInfo;
import ntd.util.config.common.bo.ResponseBO;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/task")
public class ControllerTask {

    @PostMapping("{task}/{dataCode}")
    public ResponseBO distribution(@RequestBody(required = false) String body,
                                   @RequestParam Map<String, String> params,
                                   @PathVariable("dataCode") String dataCode,
                                   @PathVariable("task") String taskCode
    ) {
        TaskInfo taskInfo = TaskManager.get(taskCode);
        if (ObjectUtil.isNull(taskInfo)) {
            return ResponseBO.err("没有匹配的任务！");
        }

        taskInfo.getTask().execute(new RequestInfo().setBody(ObjectUtil.defaultIfNull(body, ""))
            .setParams(params).setDataCode(dataCode));

        return new ResponseBO<>();
    }

    @GetMapping
    public ResponseBO<JSONObject> list() {
        List<JSONObject> jsonObjects = CollStreamUtil.toList(TaskManager.list(), actionInfo -> {
            JSONObject obj = JSONUtil.createObj();
            obj.set("taskCode", actionInfo.getTaskCode());
            obj.set("name", actionInfo.getName());
            return obj;
        });

        return new ResponseBO<>(jsonObjects);
    }
}
